/**
 * 
 */
package IC.Analyzer;

import java.util.HashMap;
import java.util.Map;

/**
 *
 */
public class SymTable {
	private SymTable parent;
	private Map<String,SymTabEntry> entries;

	/* holds the nesting depth */
	private int depth;

	public SymTable(SymTable parent) {
		this.parent = parent;
		entries = new HashMap<String,SymTabEntry>();
		depth = (parent == null)?0:(parent.depth+1);
	}

	/**
	 * add an entry to the symbol table
	 * @param id
	 * @param entry
	 */
	public void add(String id, SymTabEntry entry) {
		entries.put(id, entry);
		entry.setDepth(depth);
	}


	/**
	 * @param id
	 * @return the entry of 'id', recursively
	 */
	public SymTabEntry resolve(String id) {
		SymTabEntry e;
		if ((e = entries.get(id)) != null) {
			return e;
		} else if (parent != null) {
			return parent.resolve(id);
		} else {
			return null;
		}
	}

	/**
	 * @param id the id to check
	 * @return whether the id is already defined in the current context
	 */
	public boolean isDefinedHere(String id) {
		return (entries.get(id) != null);
	}

	/**
	 * @param id the id to check
	 * @param kind the kind of the definition
	 * @return whether the id is already defined
	 */
	public boolean isDefined(String id) {
		return resolve(id) != null;
	}

	/**
	 * @return the parent
	 */
	public SymTable getParent() {
		return parent;
	}

	public String toString() {
		StringBuffer s = new StringBuffer("[  \n");
		for (String key : entries.keySet()) {
			s.append(key+": "+entries.get(key)+"\n");
		}
		s.append("]");
		return s.toString();
	}
}
